package org.example.commonapi.response.speechSynthesis;

import com.google.gson.Gson;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

@Data
@Slf4j
public class SpeechSynthesisListener extends WebSocketListener {
    public StringBuilder totalAnswer;
    public SpeechSynthesisListener(StringBuilder totalAnswer) {
        this.totalAnswer = totalAnswer;
    }
    private Gson gson = new Gson();
    /**
     * websocket连接关闭标志
     */
    private Boolean wsCloseFlag = false;
    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        SpeechSynthesisResponse speechSynthesisResponse = gson.fromJson(text, SpeechSynthesisResponse.class);
        if (speechSynthesisResponse.getCode() != 0) {
            log.info("发生错误，错误码为：" + speechSynthesisResponse.getCode());
            log.info("本次请求的sid为：" + speechSynthesisResponse.getSid());
            webSocket.close(1000, speechSynthesisResponse.getData().getAudio());
        }
        String content = speechSynthesisResponse.getData().getAudio();
        if ( content != null ) {
            totalAnswer.append(content);
        }
        System.out.println(speechSynthesisResponse.getData().getStatus());
        if (speechSynthesisResponse.getData().getStatus() == 2) {
            // 可以关闭连接，释放资源
            webSocket.close(1000,"");
            System.out.println("关闭资源");
            wsCloseFlag = true;
        }
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        super.onFailure(webSocket, t, response);
        if (response != null) {
            int code = response.code();
            try {
                log.info("[Spark-chat-websocket]failure code:{} , boyd{}", code, response.body().string());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
